package com.itheima.exception;

import com.itheima.support.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionInvoker {

    @ExceptionHandler
    public Result<String> invokerException(Exception e){
        String msg = e.getMessage();
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            msg = exception.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        }else if(e.getMessage() != null && e.getMessage().length() > 250){
            msg = e.getMessage().substring(0,250);
        }
        e.printStackTrace();
        return Result.buildError(msg);
    }

}
